
import GameAppConfig from "../../GameAppConfig ";
import { C2GS, GS2C } from "../protobuf/proto/Message";

export default class SocketManager extends cc.EventTarget{
    count = 0;
    wsocket:WebSocket = null;
    connecting = false;
    willSendDataStr = null;
    needShowErrorTips = true;

    private _tickkey:number = -1;
    private _connectTimes:number = 0 ;

    private RE_CONNECT_TIMES:number = 10;
    static _instance:SocketManager = null;

    static get instance(){
        if(this._instance == null){
            this._instance = new SocketManager();
        }
        return this._instance;
    }


    public resetConnectTimes(){
        this._connectTimes = 0;
        console.log("111  resetConnectTimes  this._connectTimes = "+this._connectTimes);
    }

    public doReLogin(){
        let self = this;
        self.resetConnectTimes();
        self.willSendDataStr = null;
        if(self._tickkey > 0){
            clearTimeout(self._tickkey);
            self._tickkey = -1;
        }
    }

    content(){
        this.connecting = true;
        this.needShowErrorTips = true;
        let url = "ws://" + GameAppConfig.socektIP+ ":" + GameAppConfig.socketPort +"/ws";
        // let url = "ws://58.17.73.110";
        this.wsocket = new WebSocket(url);
        console.log("connecting");
        let self = this;
        self.connecting = false;
        this.wsocket.onopen = function (event) {
            console.log(event);
            // if(self.wsocket){
            //     console.log("self.wsocket.readyState = "+self.wsocket.readyState+"  "+ (self.wsocket.readyState === WebSocket.OPEN));
            // }
            if(self.wsocket && self.wsocket.readyState == WebSocket.OPEN){
                
                if(self._connectTimes > 0 && self._connectTimes != 100){
                    // self.resetConnectTimes();
                    // self.willSendDataStr = null;
                    // if(self._tickkey > 0){
                    //     clearTimeout(self._tickkey);
                    //     self._tickkey = -1;
                    // }
                    // ControlManager.loginControl.reLogin();
                    // ViewManager.ins().close(ViewConst.AlertView);
                    self.doReLogin();
                    console.log("==========dorelogin1");
                    return;
                }
            }
        };

        this.wsocket.binaryType = 'arraybuffer';
        this.wsocket.onmessage = function (event) {
            let dataType = typeof event.data;
            if(dataType == "object"){
                var buf = new Uint8Array(event.data);
                let data = GS2C.decode(buf);
                if(data){
                    
                    let id = data.protocolId;
                    SocketManager.instance.emit(id, data[id]);
                }
            }
        };
        this.wsocket.onerror = function (event) {
            self.connecting = false;
            self.netErroTips();
            console.log("error");
        };
        this.wsocket.onclose = function (event) {
            self.connecting = false;
            console.log("close");
        };

        // setTimeout(function () {
        //     if (self.wsocket.readyState === WebSocket.OPEN) {
                
        //     }else {
        //         console.log("WebSocket instance wasn't ready...");
        //     }
        // }, 3000);
    }

    disconnect(){
        this.needShowErrorTips = false;
        if(this.wsocket && this.wsocket.readyState === WebSocket.OPEN){
            this.wsocket.close();
        }
        this.wsocket = null;
    }
    

    send(sendId, data){
        let c2gs = C2GS.create();
        c2gs[sendId] = data;
        c2gs.protocolId = sendId;
        let sendBuff = C2GS.encode(c2gs).finish();
        if(this.wsocket && this.wsocket.readyState === WebSocket.OPEN){
            this.wsocket.send(sendBuff);
        }else{
            console.log("网络没有连接");
            this.willSendDataStr = sendBuff;
            if(this.connecting){
                return;
            }
            this.content();
            // this.netErroTips();
        }
    }

    netErroTips(){
        if(!this.needShowErrorTips){
            if(this._tickkey > 0){
                clearTimeout(this._tickkey);
                this._tickkey = -1;
            }
            return;
        }

        let self = this;
        console.log("=======================neterror");
        let okcall = function(){
            // console.log("ok按钮点击", UserInfo.getUserName());
            // if(UserInfo.getUserName() && UserInfo.getUserName() != null){
            //     //已经登录过了，直接进行登录操作
            //     userModel.loginRequest(UserInfo.getUserName());
            // }else{
            //     self.content();
            // }
        };

        let cancelcall = function(){

        };
        console.log("222  netErroTips  this._connectTimes = "+this._connectTimes);
        if(this._connectTimes >= this.RE_CONNECT_TIMES){
            console.log("重连失败，回到登录界面");
          
            return ;
        }

        if(this._tickkey > 0){
            clearTimeout(this._tickkey);
            this._tickkey = -1;
        }
        
        
        //网络中断
        this._tickkey = setTimeout(() => {
            this._connectTimes++;
            console.log("444  netErroTips  this._connectTimes = "+this._connectTimes);
            console.log("尝试重连，第"+this._connectTimes+"次");
            this.content();
            if(this._tickkey > 0){
                clearTimeout(this._tickkey);
                this._tickkey = -1;
            }
        }, 1000);
    }

}